<?php
	require_once ("../../config.php");
	
	# Verify what button was clicked.
	$btaction = $_POST['submit_loginadd'];
	if ($btaction == "Voltar"){
		header("Location: /itcontrol/com/main/main.php");
	}else{
	
		# Push data from form
		$values[0] = $_POST['input_name'];
		$values[1] = $_POST['input_lastname'];
		$values[2] = $_POST['input_login'];
		$values[3] = $_POST['input_psw'];
		$values[4] = $_POST['input_email'];
		
		# Array contains the fields that we'll use
		$fields[0] = "name";
		$fields[1] = "lastname";
		$fields[2] = "login";
		$fields[3] = "psw";
		$fields[4] = "email";
		
		# Array contains the Alias of fields
		$namefields[0] = "Nome";
		$namefields[1] = "Sobrenome";
		$namefields[2] = "Login";
		$namefields[3] = "Senha";
		$namefields[4] = "Email";
		
		# Set the boolean variable FALSE
		$error = FALSE;
		
		# Check if there is one or more empty fields. Having a empty field then change the value of $error and redirect to the add login page with the 
		# previous inserted data
		if (empty($values[0])){
			$error = TRUE;
		}
		if (empty($values[1])){
			$error = TRUE;
		}
		if (empty($values[2])){
			$error = TRUE;
		}
		if (empty($values[3])){
			$error = TRUE;
		}
		if (empty($values[4])){
			$error = TRUE;
		}
		
		# Store data
		if ($error == TRUE) {
			
			# Transform data to be able to send as parameter
			$values = urlencode(implode(",", $values));
			
			# Redirect to add login page with the previous inserted data
			header("Location: /itcontrol/com/main/login/login_add.php?return=".$values);
		}else {	
			
			# Connect with database
			$dbconnection = new connectDB();
			
			# Check if name, lastaname or login exist on DB
			$chkvalues[0] = $fields[0]. "='" .$values[0]. "'";
			$chkvalues[1] = $fields[1]. "='" .$values[1]. "'";
			$chkvalues[2] = $fields[2]. "='" .$values[2]. "'";
			$check = $dbconnection->checkDB("tb_login","login", "add", $fields, $namefields, $chkvalues);

			# If doesn't exist, insert data. Else shows error message 
			if ($check == 0) {
				
				# Insert data
				$insert = $dbconnection->insertDB("tb_login", "login", "add", $fields, $namefields, $values);
				$insert = "login-add-" .$insert;
			}else{
				
				# Error message
				$insert = "login-add-fail";
			}	
			
			
			# Disconnect with DB
			$dbconnection->disconnectDB();
			
			# Redirect to main page and show the result (positive or negative)
			header("Location: /itcontrol/com/redirect/redirect.php?action=".$insert);
		}	
	}
?>